//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using SR = Microsoft.Research.DataLayer;

namespace Webhost
{
    public class Global : System.Web.HttpApplication
    {
        private const string DEFAULT_PAGE_PATH = "Default.aspx";
        private const string QUERY_STRING_AUTHENTICATE_KEY = "Authenticate";

        private static SR.Connection m_registryConnection;

        /// <summary>
        /// Gets the registry connection.
        /// </summary>
        /// <value>The registry connection.</value>
        public static SR.Connection RegistryConnection
        {
            get
            {
                return m_registryConnection;
            }
        }

        private void Application_Start(object sender, EventArgs e)
        {
            SR.SR_Connection.Init();
            SR.ConnectionManager.AlternateProviderLocation = System.Web.HttpRuntime.BinDirectory;

            SR.ConnectionManager mgr = SR.ConnectionManager.CreateForAgent(
                SR.ConnectionManager.CancelBehavior.ThrowException,
                SR.ConnectionManager.Agent.WebService);
            m_registryConnection = mgr.PickConnection(SR.ConnectionManagerBase.ConnectionUI.NeverShowUI);
        }

        private void Session_Start(object sender, EventArgs e)
        {

        }

        private void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        private void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            ///Prompt user for windows credentails
            HttpRequest request = HttpContext.Current.Request;
            bool authenticate = false;
            if (request.QueryString[QUERY_STRING_AUTHENTICATE_KEY] != null)
            {
                bool.TryParse(request.QueryString[QUERY_STRING_AUTHENTICATE_KEY], out authenticate);
            }

            if (authenticate && (!request.IsAuthenticated))
            {
                ////Send unauthorized response
                Response.StatusCode = 401;
            }
        }

        private void Application_Error(object sender, EventArgs e)
        {

        }

        private void Session_End(object sender, EventArgs e)
        {

        }

        private void Application_End(object sender, EventArgs e)
        {

        }
    }
}